package com.bulletelc.apollopre.module.display.product.resultList.fragment;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.entity.SearchResultGoodsBean;
import com.bulletelc.apollopre.framework.BasePresenter;
import com.bulletelc.apollopre.utils.LogUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by CX on 2018/4/12.
 */

public class ResultListPresenter extends BasePresenter<ResultListContact.View> implements ResultListContact.Presenter {

    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }

    @Override
    public void searchByName(int page, String... args) {
        searchByNameImp(page, args);
    }

    @Override
    public void searchByClassifyId(int page, String... args) {
        searchByClassifyIdImp(page, args);
    }

    /**
     * 通过name搜索商品
     */
    private void searchByNameImp(int page, String... args) {
        OkGo.<String>get(NetWorkPath.GET_PRODUCT_LIST + "?Product[sku]=" + args[0] + "&sort=" + args[1] + "&page=" + page)
                .params("access_token", MyApplication.getToken())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorByName(response.getException().toString());
                        }
                    }
                });

    }

    /**
     * 解析通过name搜索商品返回的数据
     *
     * @param response
     */
    private void parseData(Response<String> response) {
        if (response.isSuccessful()) {
            try {

                JSONObject object = new JSONObject(response.body().toString());
                JSONObject objMeta = new JSONObject(object.getString("meta"));
                List<SearchResultGoodsBean> productList = new ArrayList<>();
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(objMeta.getString("code"))) {
                    JSONArray objSub = object.getJSONArray("data");
                    for (int i = 0, size = objSub.length(); i < size; i++) {
                        SearchResultGoodsBean good = new SearchResultGoodsBean();
                        good.setId(objSub.getJSONObject(i).getString("id"));
                        good.setGoodName(objSub.getJSONObject(i).getString("name"));
                        good.setLowest_price(objSub.getJSONObject(i).getDouble("lowest_price"));
                        good.setOriginalPrice(objSub.getJSONObject(i).getString("sales_price"));
                        good.setImgUrl(objSub.getJSONObject(i).getString("originalUrl"));
                        good.setSold(objSub.getJSONObject(i).getInt("sold"));
                        good.setComment_count(objSub.getJSONObject(i).getInt("comment_count"));
                        productList.add(good);
                    }
                    JSONObject extraObj = new JSONObject(objMeta.getString("extraData"));
                    int totalPage = extraObj.getInt("pageCount");

                    if (isViewAttached()) {
                        getView().onSuccessByName(productList, totalPage);
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailByName(objMeta.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorByName("解析数据有误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailByName(response.body().toString());
            }
        }
    }


    /**
     * 通过分类ID搜索商品
     *
     * @param args
     */
    private void searchByClassifyIdImp(int page, String... args) {
        LogUtil.i("-------"+NetWorkPath.GET_PRODUCT_LIST + "?cids=[" + args[0] + "]" + "&sort=" + args[1] + "&page=" + page);
        OkGo.<String>get(NetWorkPath.GET_PRODUCT_LIST + "?cids=" +args[0] + "&sort=" + args[1] + "&page=" + page)
                .params("access_token", MyApplication.getToken())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseByClassify(response);
                    }
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorByClassifyId(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解析通过name搜索商品返回的数据
     *
     * @param response
     */
    private void parseByClassify(Response<String> response) {
        if (response.isSuccessful()) {
            try {

                JSONObject object = new JSONObject(response.body().toString());
                JSONObject objMeta = new JSONObject(object.getString("meta"));
                List<SearchResultGoodsBean> productList = new ArrayList<>();
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(objMeta.getString("code"))) {
                    JSONArray objSub = object.getJSONArray("data");
                    for (int i = 0, size = objSub.length(); i < size; i++) {
                        SearchResultGoodsBean good = new SearchResultGoodsBean();
                        good.setId(objSub.getJSONObject(i).getString("id"));
                        good.setImgUrl(objSub.getJSONObject(i).getString("originalUrl"));
                        good.setGoodName(objSub.getJSONObject(i).getString("name"));
                        good.setLowest_price(objSub.getJSONObject(i).getDouble("lowest_price"));
                        good.setOriginalPrice(objSub.getJSONObject(i).getString("sales_price"));
                        good.setSold(objSub.getJSONObject(i).getInt("sold"));
                        good.setComment_count(objSub.getJSONObject(i).getInt("comment_count"));
                        productList.add(good);
                    }

                    JSONObject extraObj = new JSONObject(objMeta.getString("extraData"));
                    int totalPage = extraObj.getInt("pageCount");

                    if (isViewAttached()) {
                        getView().onSuccessByClassifyId(productList, totalPage);
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailByClassifyId(objMeta.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorByClassifyId("解析数据有误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailByClassifyId(response.body().toString());
            }
        }
    }

}
